﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TrangTrai.Data.DAO;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxTabControl;

namespace Trangtrai.tochuc
{
    public partial class AoManage : System.Web.UI.Page
    {
        GroupManagementDAO dao = new GroupManagementDAO();
        AoManageDAO aoDao = new AoManageDAO();
        static Dictionary<string, int> seasonDic = new Dictionary<string,int>();
        static Dictionary<string, int> groupDic = new Dictionary<string, int>();
        static Dictionary<string, int> statusDic = new Dictionary<string, int>();
        static int _aoId=-1;
        static int _seasonId=-1;
        static int _aoSeasonId = -1;
        static SeasonInfo []arrSeasons=null;
        static GroupInfo[] arrGroupInfos=null;
        AoInfo _oldAoInfo = null;
        #region common page
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                seasonDic = dao.getSeasonList().ToDictionary(x => x.seasonName, x => x.seasonId);
                groupDic = dao.getAllGroupListByLinq().ToDictionary(x => x.groupCode, x => x.groupId);
                statusDic = dao.getAoStatus().ToDictionary(x => x.statusName, x => x.aoStatusId);
                //fillDataTachAoTab();
                //init();
                arrSeasons = dao.getSeasonList();
                arrGroupInfos = dao.getAllGroupListByLinq();
                fillDataTiaAoTab();
                fillDataThaTomTab();
                fillDataTachAoTab();
                fillDataDetailsTab();
            }
            // fill data into tabpage controll
            // get all tabpages
            //TabPage tpThatom= tpCtrls.TabPages.FindByName("tbthatom");
            // set data into tha tom tab page
            // init data for tha tom tab            
            init();
        }
        private void init()
        {
            
            cbxStatus.DataSource = dao.getAoStatus();
            cbxStatus.DataBind();
            cbxGroupManage.DataSource = arrGroupInfos;
            cbxGroupManage.DataBind();
            dtgAoMan.DataSource = dao.getAoManagementList();
            dtgAoMan.DataBind();
        } 
        #endregion

        #region thong tin chi tiet ao
        private void fillDataDetailsTab() {
            AoInfo []aoInfo= dao.getActiveAoList();
            cbDetailsAoCode.DataSource=aoInfo;
            cbDetailsAoCode.DataBind();
            cbDetailsSeason.DataSource = arrSeasons;
            cbDetailsSeason.DataBind();

        }
        protected void btnDetailsView_Click(object sender, EventArgs e)
        {
             int seasonId = (int)cbDetailsSeason.SelectedItem.Value;
             int aoId = (int)cbDetailsAoCode.SelectedItem.Value;
             AoDetails aoDetails= aoDao.getAoDetailsById(aoId, seasonId);
             AoEnvDetails aoEnv = aoDao.getEnvDetails(aoId, seasonId);

        }
        private void loadDataDetailsToControls(AoDetails aoDetails, AoEnvDetails aoEnv) {
            // thong tin chi tiet cua ao tom
            lbAoName.Text = aoDetails.aoName;
            lbTomAge.Text = aoDetails.age == null ? "" : aoDetails.age.ToString();
            lbNumberTom.Text = aoDetails.amount==null? "" : aoDetails.amount.ToString();;
            lbDatePutTom.Text = aoDetails.ngaytha.ToShortDateString();
            lblArea.Text = aoDetails.dienTich.ToString();
            lbStatus.Text = aoDetails.statusName;
            lbDeepWater.Text = aoDetails.mucnuoc.ToString();
            lbGroupManage.Text = aoDetails.groupName;
            lbNote.Text = aoDetails.note;

            // thong tin ve ky thuat cua ho tom
            lbDoMan.Text = aoEnv.doMan.ToString();
            lbOXY.Text = aoEnv.bod.ToString();
            lbDoKiem.Text = aoEnv.doKiem.ToString();
            lbCOD.Text = aoEnv.cod.ToString();
            lbNH.Text = aoEnv.aoNh.ToString();
            lbDO.Text = aoEnv.aoDo.ToString();
            lbDoTrong.Text = aoEnv.doTrong.ToString();
            lbSizeTom.Text = aoEnv.tomSize.ToString();
            //lbHealthStatus.Text= aoEnv.s
            lbWaterColor.Text = aoEnv.mauNuoc;

        }
        #endregion

        #region tach ao tab page
        private void fillDataTachAoTab()
        {
            cbxOldAoCode.DataSource = dao.getActiveAoList();
            cbxOldAoCode.DataBind();
            cbxOldAoCode.SelectedIndex = -1;
            cbxOldAoSeason.DataSource = arrSeasons;
            cbxOldAoSeason.DataBind();
            // get tat ca doi san xuat
            cbxSpilitAoGroup.DataSource = arrGroupInfos;
            cbxSpilitAoGroup.DataBind();
            // get tat ca loai tom giong
            cbxSpilitAoSeason.DataSource = arrSeasons;
            cbxSpilitAoSeason.DataBind();
        }
        protected void cbxOldAoCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            // load data detail for ao
            _aoId= (int) cbxOldAoCode.SelectedItem.Value;
            AoInfo aoInfo= dao.getAoById(_aoId).First();
            _seasonId =(int) aoInfo.seasonId;
            AoSeasonEntry temp = aoDao.getIdByAoAndSeason(_aoId, _seasonId);
            _aoSeasonId = temp == null ? -1 : temp.aoSeasonId; 
            // fill data group combo
            cbxOldAoGroup.Items.Clear();
            cbxOldAoGroup.Items.Add(aoInfo.groupName, aoInfo.groupId);
            cbxOldAoGroup.SelectedIndex = 0;           
            tbxNoteOldAo.Text = aoInfo.note;
            tbxOldAoName.Text = aoInfo.aoName;
            
        }
        protected void btnSpilitAo_Click(object sender, EventArgs e)
        {
            ThaTom thatom = dao.getThaTomById(_aoId, _seasonId);
            // lay thong tin cua ao cu
            _oldAoInfo = dao.getAoById(_aoId).First();
            // reset data for old ao
            #region tach ao, su ly cho ao cu
            TiaAo oldAoInfo = getDataForOldAo(thatom);
            aoDao.TiaAo(oldAoInfo);
            // update luong thuc an va hoa chat cua ao cu

            ChoAnLog[] arr = aoDao.getChoAnLogs(_aoSeasonId, oldAoInfo.ngaytia);
            for (int i = 0; i < arr.Length; i++)
            {
                aoDao.updateCuanHis(arr[i].choanId, oldAoInfo.remain);
                aoDao.updateHoachatHis(arr[i].choanId, oldAoInfo.remain);
            } 
            #endregion

            // create new ao and kich hoat tha tom
            AoInfo newAoInfo = getDataForNewAo(thatom);
            dao.createAo(newAoInfo);
            int aoId = aoDao.getAoIdByAoCode(newAoInfo.aoCode);
            // insert ao_id and season_id into ao_season table
            aoDao.createAoSeason(aoId, (int)newAoInfo.seasonId);
            // get ao_season
            AoSeasonEntry temp = aoDao.getIdByAoAndSeason(aoId, (int)newAoInfo.seasonId);
            
            int aoSeasonId= temp == null ? -1 : temp.aoSeasonId;
            // kich hoat tha tom cho ao moi
            thatom.seasonId = aoSeasonId;
            float percentForNewAo= float.Parse(tbxSpilitUnit.Text.Substring(0, tbxSpilitUnit.Text.IndexOf("%"))) / 100;
            thatom.amount = (int)(percentForNewAo * thatom.amount);
            // ngay kich hoat tha tom cua ao moi la ngay tach cua ao cu.
            thatom.ngayTha = (DateTime)cbxSplitDate.Value;
            dao.activeAo(thatom);

            // phan chia chi phi cua ao cu cho ao moi
            //get all log_id
             ChoAnLog[] choanLogs= aoDao.getChoAnLogs(_aoSeasonId, newAoInfo.createdDate);
             foreach(ChoAnLog log in choanLogs){
                   aoDao.insertChoAnLog(log);
             }
             // duplicate cuanHis
            // lay danh sach choan log cua ao moi.

             ChoAnLog[] _choanLogs= aoDao.getChoAnLogs(aoSeasonId, newAoInfo.createdDate);

             for (int i=0;i< choanLogs.Length;i++)
             {
                 //get danh sach cu an theo log_id cua ao cu
                 CuAnHisEntry[] cuanList = aoDao.getCuanHis(choanLogs[i].choanId);
                // insert du lieu cu an cho ao moi
                 foreach(CuAnHisEntry cuan in cuanList){
                     cuan.choanId = _choanLogs[i].choanId;
                     cuan.actualAmount =(int) percentForNewAo * cuan.actualAmount;
                     aoDao.InsertCuAnHis(cuan);
                 }
                 //
                 HoaChatHisEntry[] hoachatList = aoDao.getHoaChatHis(choanLogs[i].choanId);
                 // them du lieu 
                 foreach(HoaChatHisEntry item in hoachatList){
                     item.choanId = _choanLogs[i].choanId;
                     item.value = (int)percentForNewAo * item.value;
                     aoDao.InsertHoaChatHis(item);
                 }

             }
             //lay danh sach log_id cua ao moi

             

        }
        private AoInfo getDataForNewAo(ThaTom thatom) {
            AoInfo newAoInfo = new AoInfo();
            newAoInfo.aoCode = tbxSpilitAoCode.Text;
            newAoInfo.aoName = tbxSpilitAoName.Text;
            newAoInfo.groupId = (int)cbxSpilitAoGroup.Value;
            newAoInfo.seasonId = (int)cbxSpilitAoSeason.Value;
            newAoInfo.createdDate = _oldAoInfo.createdDate;
            newAoInfo.note = tbxNoteNewAo.Text;
            return newAoInfo;
        }
        private TiaAo getDataForOldAo(ThaTom thatom)
        {
            TiaAo oldAoInfo = new TiaAo();
            oldAoInfo.aoId = (int)cbxOldAoCode.SelectedItem.Value;
            oldAoInfo.aoName = tbxOldAoName.Text;
            oldAoInfo.groupId = (int)cbxOldAoGroup.Value;
            oldAoInfo.seasonId = (int)cbxOldAoSeason.Value;
            oldAoInfo.ngaytia = (DateTime)tbxDateTime.Value;
            oldAoInfo.note = tbxNoteOldAo.Text;
            oldAoInfo.remain = thatom.amount == 0 || thatom.amount == -1 ? -1 : float.Parse(tbxExistNumberTom.Text.Substring(0, tbxExistNumberTom.Text.IndexOf("%"))) / 100;
            oldAoInfo.aoSeasonId = _aoSeasonId;
            return oldAoInfo;

        }

        #endregion


        #region them ao moi
        public AoInfo getDataFromControls()
        {
            AoInfo aoInfo = new AoInfo();

            aoInfo.createdDate = DateTime.Parse(tbxDateTime.Text);
            aoInfo.groupId = Int16.Parse(cbxGroupManage.SelectedItem.Value.ToString());
            aoInfo.aoCode = tbxAOCode.Text.Trim();
            aoInfo.aoName = tbxAoName.Text.Trim();
            aoInfo.dienTich = float.Parse(tbxArea.Text.Trim());
            aoInfo.doSau = float.Parse(tbxDeep.Text.Trim());
            aoInfo.note = tbxNote.Text.Trim();
            aoInfo.aoStatusId = Int16.Parse(cbxStatus.SelectedItem.Value.ToString());
            return aoInfo;
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            AoInfo aoInfo = getDataFromControls();
            dao.createAo(aoInfo);
            lblMess.Text = "Thêm mới ao thành công";
            refreshData();

        } 
        #endregion
  

        #region quan ly ao tom
        protected void dtgAoMan_CellEditorInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs e)
        {
            if (!dtgAoMan.IsEditing || e.Column.FieldName == "aoCode") return;
            //if (e.KeyValue == DBNull.Value || e.KeyValue == null) return;
            // object val1 = dtgAoMan.GetRowValuesByKeyValue(e.KeyValue, "seasonName");
            // if (val1 == DBNull.Value) val1="";
            // string seasonName = (string)val1;
            else if (e.Column.FieldName == "seasonName")
            {
                ASPxComboBox combo = e.Editor as ASPxComboBox;
                FillData(combo, e.Column.FieldName);
                combo.Callback += new CallbackEventHandlerBase(cmbSeason_OnCallback);
            }
            else if (e.Column.FieldName == "groupCode")
            {
                ASPxComboBox combo = e.Editor as ASPxComboBox;
                FillData(combo, e.Column.FieldName);
                combo.Callback += new CallbackEventHandlerBase(cmbGroup_OnCallback);
            }
            else if (e.Column.FieldName == "statusName")
            {
                ASPxComboBox combo = e.Editor as ASPxComboBox;
                FillData(combo, e.Column.FieldName);
                combo.Callback += new CallbackEventHandlerBase(cmbStatus_OnCallback);
            }

        }

        private void cmbSeason_OnCallback(object source, CallbackEventArgsBase e)
        {
            FillData(source as ASPxComboBox, "seasonName");
        }
        private void cmbGroup_OnCallback(object source, CallbackEventArgsBase e)
        {
            FillData(source as ASPxComboBox, "groupCode");
        }
        private void cmbStatus_OnCallback(object source, CallbackEventArgsBase e)
        {
            FillData(source as ASPxComboBox, "statusName");
        }

        protected void FillData(ASPxComboBox cmb, string fileName)
        {
            //if (string.IsNullOrEmpty(value)) return;

            //List<string> cities = dao.getRoles();            
            //Role[] roles = dao.getRoles();
            if (fileName.Equals("seasonName", StringComparison.OrdinalIgnoreCase))
            {
                SeasonInfo[] seasons = dao.getSeasonList();
                cmb.DataSource = seasons;

                cmb.DataBind();
            }
            else if (fileName.Equals("groupCode", StringComparison.OrdinalIgnoreCase))
            {
                cmb.DataSource = dao.getAllGroupListByLinq();
                cmb.DataBind();
            }
            else if (fileName.Equals("statusName", StringComparison.OrdinalIgnoreCase))
            {
                cmb.DataSource = dao.getAoStatus();
                cmb.DataBind();
            }

        }

        protected void dtgAoMan_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            AoManagement aoMan = new AoManagement();
            aoMan.aoSeasonId = Int32.Parse(e.Keys[0].ToString());
            aoMan.seasonId = e.NewValues["seasonName"] == null ? seasonDic[e.OldValues["seasonName"].ToString()] : Int32.Parse(e.NewValues["seasonName"].ToString());
            aoMan.groupId = e.NewValues["groupCode"] == null ? groupDic[e.OldValues["groupCode"].ToString()] : Int32.Parse(e.NewValues["groupCode"].ToString());
            aoMan.aoStatusId = e.NewValues["statusName"] == null ? statusDic[e.OldValues["statusName"].ToString()] : Int32.Parse(e.NewValues["statusName"].ToString());
            aoMan.note = e.NewValues["note"] == null ? e.OldValues["note"].ToString() : e.NewValues["note"].ToString();
            dao.updateAoSeason(aoMan);
            refreshData();
            e.Cancel = true;
        }

        private void refreshData()
        {
            dtgAoMan.DataSource = dao.getAoManagementList();
            dtgAoMan.DataBind();
        } 
        #endregion


        #region kich hoat tha tom
        protected void btnActive_Click(object sender, EventArgs e)
        {
            //get data from kich hoat ao tha tom
            ThaTom thatom = new ThaTom();
            thatom.aoId = (int)cbAoCode.SelectedItem.Value;
            thatom.ngayTha = (DateTime)dtNgayTha.Value;
            thatom.tomId = (int)cbTomCategory.SelectedItem.Value;
            thatom.amount = Int32.Parse(txtAmount.Text);
            //thatom.mucnuoc = float.Parse(txtMucNuoc.Text);
            thatom.mucnuoc = decimal.Parse(txtMucNuoc.Text);
            thatom.note = txtNote.Text;
            thatom.seasonId = (int)cbSeason.SelectedItem.Value;
            dao.activeAo(thatom);
        }

        private void fillDataThaTomTab()
        {
            cbAoCode.DataSource = dao.getAoList();
            cbAoCode.DataBind();
            // get tat ca doi san xuat
            cbGroup.DataSource = dao.getAllGroupListByLinq();
            cbGroup.DataBind();
            // get tat ca loai tom giong
            cbTomCategory.DataSource = dao.getTomList();
            cbTomCategory.DataBind();
            // get season list
            cbSeason.DataSource = dao.getSeasonList();
            cbSeason.DataBind();
        }

        #endregion
        #region Tia ao
        protected void btnTia_Click(object sender, EventArgs e)
        {

            TiaAo tiaAo = new TiaAo();
            tiaAo.aoId = (int)tbxAoCodeTia.SelectedItem.Value;
            tiaAo.seasonId = (int)cbxSeasonTia.SelectedItem.Value;
            tiaAo.groupId = (int)cbxGroupTia.SelectedItem.Value;
            tiaAo.remain = float.Parse(tbxPercenTomTia.Text.Substring(0,tbxPercenTomTia.Text.IndexOf("%")))/100;
            tiaAo.ngaytia =(DateTime) cbxDateGet.Value;
            tiaAo.note = tbxNoteTia.Text.Trim();
            tiaAo.aoSeasonId = _aoSeasonId;
            tiaAo.aoName = tbxAoNameTia.Text.Trim();
            aoDao.TiaAo(tiaAo);
            // get log_id list
           ChoAnLog [] arr= aoDao.getChoAnLogs(_aoSeasonId, tiaAo.ngaytia);
           for (int i = 0; i< arr.Length;i++ )
           {
               aoDao.updateCuanHis(arr[i].choanId, tiaAo.remain);
               aoDao.updateHoachatHis(arr[i].choanId, tiaAo.remain);
           }

            
        }

        private void fillDataTiaAoTab()
        {
            tbxAoCodeTia.DataSource = dao.getActiveAoList();
            tbxAoCodeTia.DataBind();
            cbxSeasonTia.DataSource = dao.getSeasonList();
            cbxSeasonTia.DataBind();

        }
        protected void tbxAoCodeTia_SelectedIndexChanged(object sender, EventArgs e)
        {
            int aoId = (int)tbxAoCodeTia.SelectedItem.Value;
            AoInfo[] aoInfos = dao.getAoById(aoId);
            if (aoInfos.Length == 0) return;
            AoInfo aoInfo = aoInfos.First();
            // store old ao_id and seasonid
            // start
            _aoId = aoId;
            _seasonId = aoInfo.seasonId == null ? -1 : (int)aoInfo.seasonId;
            AoSeasonEntry temp= aoDao.getIdByAoAndSeason(_aoId, _seasonId);
            _aoSeasonId = temp == null ? -1 : temp.aoSeasonId;
            // lay so luong tom tha ban dau.
            // end
            cbxGroupTia.Items.Clear();
            cbxGroupTia.Items.Add(aoInfo.groupName, aoInfo.groupId);
            cbxGroupTia.SelectedIndex = 0;
            cbxDateGet.Value = aoInfo.createdDate;
        } 
        #endregion




    }
}
